package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.InvoiceService;
import cn.itcast.service.cargo.ShippingOrderService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/invoice")
@Slf4j
public class InvoiceController extends BaseController {
    @Reference
    private InvoiceService invoiceService;
    @Reference
    private ShippingOrderService shippingService;

    /**
     * 分页查询
     *
     * @param pageNum  当前页
     * @param pageSize 页面大小
     * @return 工厂列表路径
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        InvoiceExample example = new InvoiceExample();
        //根据创建时间倒序排列（弃用与不启用的都进行展示）
        example.setOrderByClause("invoice_time desc");
        PageInfo<Invoice> pageInfo = invoiceService.findByPage(example, pageNum, pageSize);

        request.setAttribute("pageInfo", pageInfo);
        return "cargo/invoice/invoice-list";
    }

    /**
     * 新建或者修改
     *
     * @param invoice 发票对象数据
     * @return 装箱单分页查询路径
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(Invoice invoice, String invoiceId) {
        ShippingOrder shipping = shippingService.findById(invoiceId);
        if (StringUtils.isEmpty(invoice.getStatus())) {
            invoiceService.save(invoice);
            shipping.setState(1);
            shippingService.update(shipping);
        } else {
            return "cargo/shipping/shipping-list";
        }
        return "redirect:/cargo/invoice/list";
    }

    /**
     * 删除发票
     * 返回数据：{"message" : 1}
     */
    @RequestMapping("/delete")
    @ResponseBody  // 返回json字符串
    public Map<String, Integer> delete(String id) {
        Map<String, Integer> result = new HashMap<>();

        // 调用service删除
        boolean flag = invoiceService.delete(id);
        if (flag) {
            // 删除成功
            result.put("message", 1);
        } else {
            // 删除失败
            result.put("message", 0);
        }
        return result;
    }
    /**
     * 导出excel
     * @param id 发票id
     */
    @RequestMapping("/invoiceExcel")
    public void shippingExcel(String id) throws Exception {
        // 只需要把XSSF改为SXSSF
        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("发票导出");
        // 合并单元格：开始行，结束行，开始列，结束列（0018）
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        // 设置单元格宽度
        sheet.setColumnWidth(0,256*6);
        sheet.setColumnWidth(1,256*26);
        sheet.setColumnWidth(2,256*11);
        sheet.setColumnWidth(3,256*29);
        sheet.setColumnWidth(4,256*15);
        sheet.setColumnWidth(5,256*12);
        sheet.setColumnWidth(6,256*10);


        Row row = sheet.createRow(0);
        row.setHeightInPoints(36);
        // 创建第一行的第二列，合并单元格.  2019-06-->2019年6月份出货表
        Cell cell = row.createCell(1);
        String title = "发票列表";
        // 设置单元格内容
        cell.setCellValue(title);
        // 设置样式
        cell.setCellStyle(this.bigTitle(workbook));

        // 第二：导出第二行
        String[] titles = {"发票编号","报运合同号","贸易条款","贸易金额","发票时间","发票状态"};
        row = sheet.createRow(1);
        row.setHeightInPoints(26);
        for (int i = 0; i < titles.length; i++) {
            cell = row.createCell(i+1);
            cell.setCellValue(titles[i]);
            // 设置样式
            cell.setCellStyle(this.title(workbook));
        }

        // 第三：导出数据库（调用service）
        Invoice invoice=
                invoiceService.findById(id);

            int index = 2;

                    // 创建每一个数据行，从第三行开始
                    row = sheet.createRow(index++);

                    cell = row.createCell(1);
                    cell.setCellValue(invoice.getInvoiceId());

                    cell = row.createCell(2);
                    cell.setCellValue(invoice.getScNo());

                    cell = row.createCell(3);
                    cell.setCellValue(invoice.getTradeTerms().toString());

                    cell = row.createCell(4);
                    cell.setCellValue(invoice.getInvoiceMoney().toString());

                    cell = row.createCell(5);
                    cell.setCellValue(invoice.getInvoiceTime());

                    cell = row.createCell(6);
                    cell.setCellValue(invoice.getStatus());


        // 第四：导出下载
        response.setCharacterEncoding("UTF-8");
        // 设置下载响应头（浏览器会以下载方式处理响应结果）
        response.setHeader("content-disposition","attachment;filename=export.xlsx");
        ServletOutputStream out = response.getOutputStream();
        // 把excel文件流，写入到response输出流，实现下载
        workbook.write(out);
        workbook.close();
        out.close();



    }

    /**
     * 出货表的POI导出 (2) 模板导出：先读取一个有样式的excel模板，再往里面填充数据
     */
    @RequestMapping("/invoiceExcel22")
    public void printExcel22(String id) throws IOException {
        //【获取excel模板,文件流】
        InputStream in = request.getSession()
                .getServletContext()
                .getResourceAsStream("/make/xlsprint/tINVOICE.xls");

        // 第一：导出第一行
        Workbook workbook = new HSSFWorkbook(in);
        // 【获取工作表】
        Sheet sheet = workbook.getSheetAt(0);

        //【获取第一行、第一行的第二列】
       // Row row = sheet.getRow(0);
      //  Cell cell = row.getCell(1);
      //  String title ="发票列表";
        // 设置单元格内容
        //cell.setCellValue(title);

        // 【获取第三行样式】
        CellStyle[] cellStyles = new CellStyle[7];
        Row row = sheet.getRow(15);

        for (int i = 0; i < cellStyles.length; i++) {
            cellStyles[i] = row.getCell(i+1).getCellStyle();
        }

        // 第三：导出数据库（调用service）
        Invoice invoice=
                invoiceService.findById(id);
        ShippingOrder shipping = shippingService.findById(id);

        //int index = 15;

        // 创建每一个数据行，从第三行开始
       // row = sheet.createRow(index++);

        Cell cell = row.createCell(1);
        cell.setCellValue(invoice.getInvoiceId());
        cell.setCellStyle(cellStyles[0]);

        cell = row.createCell(3);
        cell.setCellValue(invoice.getInvoiceTime());
        cell.setCellStyle(cellStyles[2]);

        cell = row.createCell(6);
        cell.setCellValue(invoice.getScNo());
        cell.setCellStyle(cellStyles[5]);

        cell = row.createCell(7);
        cell.setCellValue(invoice.getPickupPhoto());
        cell.setCellStyle(cellStyles[6]);
         //index = 19;

        // 创建每一个数据行，从第三行开始
      //  row = sheet.createRow(index++);
        CellStyle[] cellStyles2 = new CellStyle[10];
         row = sheet.getRow(19);

        for (int i = 0; i < cellStyles2.length; i++) {
            cellStyles[i] = row.getCell(i+1).getCellStyle();
        }
        cell = row.createCell(1);
        cell.setCellValue(shipping.getLcNo());
        cell.setCellStyle(cellStyles[0]);

        cell = row.createCell(3);
        cell.setCellValue(shipping.getOrderType());
        cell.setCellStyle(cellStyles[2]);

        // 第四：导出下载
        response.setCharacterEncoding("UTF-8");
        // 设置下载响应头（浏览器会以下载方式处理响应结果）
        response.setHeader("content-disposition","attachment;filename=export.xlsx");
        ServletOutputStream out = response.getOutputStream();
        // 把excel文件流，写入到response输出流，实现下载
        workbook.write(out);
        workbook.close();
        out.close();
    }













    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }

}
